import type { CSSProperties } from 'react';
import React, { useImperativeHandle, useState } from 'react';
import { ChromePicker } from 'react-color';
import type { SketchPickerProps } from 'react-color/lib/components/sketch/Sketch';

const SketchPickerCu = React.forwardRef<
  { setVisible: (value: ((prevState: boolean) => boolean) | boolean) => void },
  {
    colors?: string[] | string;
  } & SketchPickerProps
>((props, ref) => {
  const [visible, setVisible] = useState(false);
  let backgroundColor = 'unset';
  const skProps = { ...props };
  if (typeof skProps.colors === 'string') {
    backgroundColor = skProps.colors;
    // @ts-ignore
    delete skProps.colors;
    skProps.color = backgroundColor;
  }
  useImperativeHandle(ref, () => ({ setVisible }));
  const styles: Record<string, CSSProperties> = {
    color: {
      width: '100%',
      height: '100%',
      borderRadius: '50%',
      background: backgroundColor,
    },
    swatch: {
      padding: 1,
      background: '#fff',
      borderRadius: '50%',
      boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
      display: 'inline-block',
      cursor: 'pointer',
      width: 20,
      height: 20,
      border: '1px solid #e8e8e8',
    },
    popover: {
      position: 'relative',
      zIndex: 2,
    },
    cover: {
      position: 'fixed',
      top: '0px',
      right: '0px',
      bottom: '0px',
      left: '0px',
    },
  };

  return (
    <>
      {!visible ? (
        <div style={styles.swatch} onClick={() => setVisible(true)}>
          <div style={styles.color} />
        </div>
      ) : null}
      {visible ? (
        <div style={styles.popover}>
          <div style={styles.cover} onClick={() => setVisible(false)} />
          <ChromePicker {...skProps} />
        </div>
      ) : null}
    </>
  );
});

export default SketchPickerCu;
